package com.mpsc.singleton.demo.controller;

import com.mpsc.singleton.demo.common.BaseResponse;
import com.mpsc.singleton.demo.entity.RoleInfoEntity;
import com.mpsc.singleton.demo.feign.MpscSpringService;
import com.mpsc.singleton.demo.service.RoleInfoService;
import com.mpsc.singleton.demo.util.ExcelUtil;
import com.mpsc.singleton.demo.util.ExportFileUtil;
import com.mpsc.singleton.demo.vo.RoleInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/roleInfo")
@Api(value = "RoleInfoController", tags = "角色管理")
public class RoleInfoController {

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private MpscSpringService mpscSpringService;

    @PostMapping("/save")
    @ApiOperation("保存用户信息")
    public void save(@RequestBody RoleInfoEntity role) {
        //测试spring事务问题
        roleInfoService.saveRoleInfo(role);
    }

    @PostMapping("/select")
    @ApiOperation("查询用户信息")
    public RoleInfoVo select(@RequestBody @Validated RoleInfoVo role) {
        System.out.println(role.toString());
        //throw new BusinessException(404, "测试错误信息！");
        BaseResponse<RoleInfoVo> response = mpscSpringService.select(role);
        System.out.println(response.getCode());
        return role;
        // return new BaseResponse(001002, "疯狂小豆丁", null);
    }

    @GetMapping("/select-one")
    @ApiOperation("查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", required = true),//多个参数时的参数说明
            @ApiImplicitParam(name = "age", value = "用户年龄", required = true)
    })
    public BaseResponse selectOne(@RequestParam String name, int age) {
        System.out.println(name);
        return new BaseResponse(001002, "疯狂小豆丁", null);
    }


    /**
     * 导出excel表格
     */
    @GetMapping("/export/excel")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        //这是表头
        String[] arr = {"roleName", "roleCode"};
        //这是具体数据
        // List<RoleInfoEntity> list = new ArrayList<>();
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("roleName", "roleName" + i);
            map.put("roleCode", "roleCode" + i);
            list.add(map);
        }
        Workbook wb = ExcelUtil.writeToExcelByList(arr, list);
        OutputStream output = response.getOutputStream();
        String fileName = "结果表.xlsx";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        wb.write(output);
        output.close();
    }

    /**
     * 导出txt 文件
     */
    @GetMapping("/export/txt")
    public void exportLog(HttpServletResponse response) {
        //这是表头
        String[] arr = {"roleName", "roleCode"};
        //这是具体数据
        List<Map<String, String>> list = new ArrayList<>();
        StringBuilder builder = new StringBuilder("roleName,roleCode").append("\r\n");
        for (int i = 0; i < 10; i++) {
            builder.append("roleName" + 1).append(",roleCode1").append("\r\n");
        }
        ExportFileUtil.exportTxt(response, builder.toString());
    }

    /**
     * 导出word文档
     */
    @GetMapping("/export/word")
    public void download(HttpServletResponse response) {
        try {
            XWPFDocument document = ExportFileUtil.generateWordXWPFDocument();
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=user_world_" + System.currentTimeMillis() + ".docx");
            OutputStream os = response.getOutputStream();
            document.write(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
